﻿using System;
using System.Collections.Generic;
using System.Linq;
using ChinapnrAPI;
using DTCash.Logger;
using DTCash.Logger.NodeLog.Model;
using DTCash.Redis;
using Uranus.Common;
using Uranus.Service.OrderService;
using Uranus.Service.OtherService;
using Uranus.Service.ProductService;
using Uranus.Service.UserService;
using Uranus.WeiStationAPI.Common;

namespace Uranus.WeiStationAPI.Models
{
    public class ControllerCommon
    {
        /// <summary>
        /// 同步产品进度
        /// </summary>
        /// <returns></returns>
        public static LoanProductDTO SyncLoanProductProgress(LoanProductDTO loanProductDto)
        {
            //确认产品购买进度

            OrderItemResponse orderItemRes = Service.Order.GetOrder().GetOrderItemsByProductCode(loanProductDto.ProductCode);
            if (orderItemRes != null && orderItemRes.OrderItemDtos != null && orderItemRes.OrderItemDtos.Count > 0)
            {
                loanProductDto.CurrentLoanPrice = orderItemRes.OrderItemDtos.Sum(a => a.OrderItemPrice);
                if (loanProductDto.ProductStatusID == 3)
                {
                    if (loanProductDto.CurrentLoanPrice >= loanProductDto.LoanPrice)
                    {
                        loanProductDto.ProductStatusID = 4;
                        loanProductDto.CurrentSchedule = 1m;
                    }
                    else
                    {
                        loanProductDto.CurrentSchedule = loanProductDto.CurrentLoanPrice / loanProductDto.LoanPrice < 0.01m ? 0.01m : loanProductDto.CurrentLoanPrice / loanProductDto.LoanPrice;
                    }
                }
                loanProductDto.OrderItemCount = orderItemRes.OrderItemDtos.Count;
            }
            if (loanProductDto.ProductStatusID >= 4)
            {
                loanProductDto.CurrentLoanPrice = loanProductDto.LoanPrice;
                loanProductDto.CurrentSchedule = 1m;
            }
            return loanProductDto;
        }

        /// <summary>
        /// 获取快速提现
        /// </summary>
        /// <returns></returns>
        public static UserBankCardDTO GetUserFastUserBankCard(int userId)
        {
            UserBankCardResponse userBankCardResponse = Service.User.GetUser().GetUserBankCardDTOList(userId);
            if (userBankCardResponse.Code != 1)
            {
                return null;
            }
            List<UserBankCardDTO> userBankCardDtos = userBankCardResponse.UserBankCardDtos.Where(p => p.UserBankCardTypeID == 2).ToList();
            if (userBankCardDtos.Count == 0)
            {
                return new UserBankCardDTO();
            }
            UserBankCardDTO userBankCardDto = userBankCardDtos.First();
            object configFastCashBank = ConfigCenterWork.GetConfigValueByOperationType(5);
            if (configFastCashBank == null)
            {
                return null;
            }
            string[] supportarray = configFastCashBank.ToString().Split(',');
            if (supportarray.Contains(userBankCardDto.BankID.ToString()))
            {
                return userBankCardDto;
            }
            return new UserBankCardDTO();
        }

        /// <summary>
        /// 获取用户活期产品可卖出金额
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public static decimal GetUserCurrentProductSellPrice(UserInfo userInfo)
        {
            if (userInfo == null || userInfo.UserID == 0)
            {
                throw new ArgumentNullException(nameof(userInfo), "userInfo is null");
            }
            //总持有活期金额
            decimal haveCurrentPrice = userInfo.CurrentInvestingPrice + userInfo.CurrentShortProfit;
            UserInvestmentResponse userInvestmentRes = Uranus.Service.Order.GetOrder().GetCurrentInvestmentDtoList(
                new Service.OrderService.UserInvestmentRequest()
                {
                    UserID = userInfo.UserID,
                    PaymentTime = DateTime.Now
                }) ?? new UserInvestmentResponse();
            if (userInvestmentRes.Code != 1)
            {
                return -1;
            }
            OrderItemTransferResponse usertodaysellRes = Uranus.Service.Order.GetOrder().GetOrderItemTransferPrice(
                new OrderItemTransferRequest
                {
                    OrderItemTransferTypeIDs = new List<int> { 3 },
                    OrderItemTransferStatusIDs = new List<int> { 2 },
                    PaymentTime = DateTime.Now,
                    UserId = userInfo.UserID
                }) ?? new OrderItemTransferResponse();
            if (usertodaysellRes.Code != 1)
            {
                return -1;
            }
            decimal todaySellMoney = (usertodaysellRes.OrderItemTransferDto ?? new OrderItemTransferDTO()).OrderItemTransferPrice;  //今日卖出活期金额
            decimal todayBuyPrice = userInvestmentRes.UserInvestmentDtos.Sum(a => a.OrderItemPrice);  //今日买入活期金额
            decimal allCanSellPrice = haveCurrentPrice - todayBuyPrice; //总持有活期金额 减去 今日买入活期金额 等于 总共可卖出活期金额
            decimal canSellPrice = CommonModel.CurrentMaximumSellOutToOneDay > 0 ? CommonModel.CurrentMaximumSellOutToOneDay - todaySellMoney : 0; //每日最大可卖出金额减去当日卖出金额等于当日可卖出金额
            canSellPrice = canSellPrice > 0 ? canSellPrice : 0;
            return canSellPrice > allCanSellPrice ? allCanSellPrice : canSellPrice;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static MerCashResponse CurrentProductMerCash(UserInfo userInfo, decimal cashPrice, int userBankCardId, Action<string> sourceHandler)
        {
            MerCashResponse merCashResponse = new MerCashResponse();
            merCashResponse.IsSuccess = false;

            Uranus.Service.UserService.BaseResponse transferResponse =
                Service.User.GetUser().InsertUserTransfer(new UserTransferRequest
                {
                    userTransferDTO = new UserTransferDTO()
                    {
                        UserTransferTypeID = UserTransferType.Cash,
                        UserID = userInfo.UserID,
                        Price = cashPrice,
                        ExtendNumber = userBankCardId,
                        UserTransferStatusID = UserTransferStatus.New,
                        FinishTime = new DateTime(1900, 1, 1),
                        UserTransferPropertyID = 11
                    }
                });
            if (transferResponse.Code != 1)
            {
                merCashResponse.ResultMsg = "活期产品卖出成功，取款到银行卡失败";
                return merCashResponse;
            }
            try
            {
                string ordId = transferResponse.ResposeData;
                string guid = Guid.NewGuid().ToString("N");
                TransactionResultCommon transactionResultCommon = new TransactionResultCommon()
                {
                    CmdID = CmdID.MerCash,
                    OrdID = ordId,
                    UserID = userInfo.UserID
                };
                CacheRedis.AddCache(new TimeSpan(5, 0, 0),
                    CacheItem.InitByIdentity("HuiFuTransaction", guid).Other.other,
                    transactionResultCommon);

                sourceHandler(ordId);
                //SourceHandle(SourceOperation.Cash, string.Empty, int.Parse(ordId), Uranus.Common.Validates.GetInt(GetParmsKey<string>("sourceTypeId")));

                ChinapnrTransaction chinapnrTransaction = new ChinapnrTransaction();
                string url = chinapnrTransaction.MerCash(ordId, userInfo.HuiFuCode,
                    cashPrice.ToString("f2"), "0.00", "MDT000001", string.Empty, ChinapnrCommon.ChinaReceiveUrl, "",
                    userInfo.UserID.ToString(), "{\"FeeObjFlag\":\"M\",\"FeeAcctId\":\"MDT000001\"}");

                Dictionary<string, object> dicParams = CodeCommon.GetUrlParams(url);
                dicParams.Add("OrdId", ordId);
                dicParams.Add("UserId", userInfo.UserID);
                DTCash.Logger.NodeLog.NodeLogHandler.AddLog("ajchuifu", "huifuinfo", "urljson", "商户代取现",
                    NodeLogType.info, dicParams);

                //先扣除用户余额
                int upd = Service.User.GetUser().UpdUsablePrice(userInfo.UserID, -1 * cashPrice);
                if (upd > 0)
                {
                    LogHelper.WriteLogInfo("减少用户余额，post进行商户代取现", $"金额:{cashPrice}",
                        new { UserId = userInfo.UserID, OrdId = ordId });

                    CacheRedis.DelCacheKeys(CacheItem.InitByIdentity(userInfo.UserID.ToString()).User.Price);

                    string res = RequestCommon.SimulationHttp(url.Split('?')[0], url.Split('?')[1], "post");

                    BaseChinapnr baseChinapnr = CodeCommon.DeSerialize<BaseChinapnr>(res);
                    if (baseChinapnr != null)
                    {
                        merCashResponse.IsSuccess = true;
                        merCashResponse.TranscationHid = guid;
                        merCashResponse.RespCode = baseChinapnr.RespCode;
                        merCashResponse.RespDesc = baseChinapnr.RespDesc;
                        merCashResponse.OrdId = baseChinapnr.OrdId;
                    }
                    else
                    {
                        merCashResponse.ResultMsg = "取现后台处理失败，请稍后再试";
                    }
                }
                else
                {
                    merCashResponse.ResultMsg = "取现后台处理失败，卖出活期产品成功";
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLogInfo("活期取现，汇付请求异常", ex.Message, new { UserId = userInfo.UserID });
                merCashResponse.ResultMsg = "网络异常";
            }
            return merCashResponse;
        }
    }
}